export const bindScroll = ({dom="body",onScroll=()=>{},onScrollBottom=()=>{}}={}) => {
  window.onscroll = () => {
    //变量scrollTop是滚动条滚动时，距离顶部的距离
    let scrollTop = document.documentElement.scrollTop || document[dom].scrollTop;
    //变量windowHeight是可视区的高度
    let windowHeight = document.documentElement.clientHeight || document[dom].clientHeight;
    //变量scrollHeight是滚动条的总高度
    let scrollHeight = document.documentElement.scrollHeight || document[dom].scrollHeight;
    //滚动条到底部的条件
    onScroll()
    if (scrollTop + windowHeight == scrollHeight) {
      onScrollBottom()
    }
  };
}

export const timer = (time, callback = () => { }) => {
  callback(time);
  if (+time === 0) {
    return () => { };
  }
  let timer = setInterval(() => {
    time = +time - 1;
    callback(time);
    if (time < 1) {
      clearInterval(timer);
    }
  }, 1000);
  return () => {
    clearInterval(timer);
  };
}

/**
 * 防抖函数，一段时间后执行回调函数
 * @param callback
 * @param delay
 * @returns {Function}
 */
export const debounce = (callback, delay, timer = null) => () => {
  const context = this, args = arguments;
  clearTimeout(timer);
  timer = setTimeout(() => {
    callback.apply(context, args);
  }, delay);
}

/**
 * 截流函数，一段时间内只能执行一次
 * @param callback
 * @param delay
 * @returns {Function}
 */
export const throttle = (callback, delay, isAvail = true) => () => {
  const args = arguments, ctx = this
  if (isAvail) {
    callback.apply(ctx, args)
    isAvail = false
    setTimeout(() => {
      isAvail = true
    }, delay)
  }
}

// 判断对象的key有没有空
export const hasBlankKey = (object,skipKeyArr = []) => {
  for (const key in object) {
    if (!skipKeyArr.includes(key)) {
      return key===undefined||key===null||key===""
    } 
  }
}

export default {
  timer
}